<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Client\Logic\Detail;

use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\Client\Contract\ClientContract;
use MoChat\App\Client\Contract\ClientTagContract;
use MoChat\App\Client\Contract\ClientTagPivotContract;

/**
 * 客户基础信息逻辑.
 *
 */
class BasicInfoLogic
{
    /**
     * @Inject
     * @var ClientContract
     */
    protected $clientService;


    /**
     * @Inject
     * @var ClientTagPivotContract
     */
    protected $clientTagPivotService;

    /**
     * @Inject
     * @var ClientTagContract
     */
    protected $clientTagService;

    /**
     * 基础信息.
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle(array $params): array
    {
        //返回的数据格式
        $data = [];
        $params['clientId']=(int)$params['clientId'];
        $data = $this->clientService->getClientById((int)$params['clientId']);
        $province = Db::table('district')->where('id', $data['province'])->value('name');
        $city = Db::table('district')->where('id', $data['city'])->value('name');
        $district = Db::table('district')->where('id', $data['district'])->value('name');
        $data['preAddress'] = $province . $city . $district;
        $data['tag'] = $this->getClientTag((int)$params['clientId']);
//        $data['contact_ids']= Db::table('client_contact_pivot')->where('client_id', (int)$params['clientId'])->pluck('contact_id')->toArray();
        $init=[
            'id'=>0,
            'name'=>$data['enterpriseName'],
            'phone'=>$data['mobile'],
            'is_default'=>1,
        ];
        $data['contact_array']= Db::table('client_phone')
            ->where('client_id',$params['clientId'])
            ->select(['name', 'id','phone','is_default'])
            ->get()->toArray();
        if (!empty($data['contact_array'])){
            $default=array_column($data['contact_array'],'is_default');
            if (!in_array(1,$default)){
                //在$data['contact_array'] 中第一个位置添加元素
                Db::table('client_phone')
                    ->where('client_id',$params['clientId'])
                    ->insert([
                        'client_id'=>$params['clientId'],
                        'name'=>$data['enterpriseName'],
                        'phone'=>$data['mobile'],
                        'is_default'=>1
                    ]);
                array_unshift($data['contact_array'],$init);
            }
        }else{
            Db::table('client_phone')
                ->where('client_id',$params['clientId'])
                ->insert([
                    'client_id'=>$params['clientId'],
                    'name'=>$data['enterpriseName'],
                    'phone'=>$data['mobile'],
                    'is_default'=>1
                ]);
            array_unshift($data['contact_array'],$init);
        }
        $data['labels'] = Db::table('client_label_relation as r')
            ->join('client_label as label','label.id','=','r.client_label_id')
            ->where('r.client_id', (int)$params['clientId'])
            ->select([
                'r.client_label_id',
                'label.name'
            ])->get();
        $data['labels'] || $data['labels']=collect([]);
        $data['labels']=$data['labels']->toArray();
        return $data;
    }

    /**
     * 获取B2B客户标签.
     * @param $clientId
     * @return array
     */
    private function getClientTag($clientId)
    {
        $clientTag = $this->clientTagPivotService->getClientTagPivotsByOtherId($clientId);
        if (empty($clientTag)) {
            return [];
        }
        $tagIds = array_unique(array_column($clientTag, 'clientTagId'));
        // 根据标签id查询标签名称
        $tagInfo = $this->clientTagService->getClientTagsById($tagIds, ['id', 'name']);
        if (empty($tagInfo)) {
            return [];
        }
        $tagInfo = array_column($tagInfo, null, 'id');
        $tagName = [];
        foreach ($clientTag as &$raw) {
            if (isset($tagInfo[$raw['clientTagId']])) {
                $tagName[] = $tagInfo[$raw['clientTagId']]['name'];
            }
        }
        unset($raw);
        $tagName = array_unique($tagName);
        return $tagName;
    }
}
